/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sistema.entidades.editor;

import br.com.sistema.excecoes.EntidadeNaoEncontrada;
import br.com.sistema.infraestrutura.ConnectionPool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Lauro
 */
public class Editor {

    private int id;
    private String usuario;
    private String senha;
    private String nome;
    private Connection conexao;

    public Editor(int id, String usuario, String nome) {
        this.id = id;
        this.usuario = usuario;
        this.nome = nome;
    }

    public static Editor getEditor(String usuario, String senha) throws SQLException {
        Connection conexao = ConnectionPool.getConnection();
        PreparedStatement query = conexao.prepareStatement(getSQLBuscarPorLogin());
        query.setString(1, usuario);
        query.setString(2, senha);
        ResultSet result = query.executeQuery();
        if (result.next()) {
            return new Editor(result.getInt("id"),
                    result.getString("usuario"),
                    result.getString("nome"));
        } else {
            return null;
        }
    }

    //<editor-fold defaultstate="collapsed" desc="Metodos Getters & Setters.">
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Connection getConexao() {
        if (conexao == null) {
            this.conexao = ConnectionPool.getConnection();
        }
        return conexao;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Strings SQL.">
    private String getSQLInsercao() {
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT INTO editor ( ");
        sql.append("   usuario, ");
        sql.append("   senha, ");
        sql.append("   nome ");
        sql.append(" ) VALUES ( ");
        sql.append("   ?, ");
        sql.append("   ?, ");
        sql.append("   ? ");
        sql.append(" ) ");
        return sql.toString();
    }

    private String getSQLAtualizacao() {
        StringBuilder sql = new StringBuilder();
        sql.append(" UPDATE ");
        sql.append(" editor ");
        sql.append(" SET ");
        sql.append(" usuario=?, ");
        sql.append(" senha=?, ");
        sql.append(" nome=? ");
        sql.append(" WHERE id = ? ");
        return sql.toString();
    }

    private String getSQLExclusao() {
        StringBuilder sql = new StringBuilder();
        sql.append(" DELETE FROM ");
        sql.append(" editor ");
        sql.append(" WHERE id = ? ");
        return sql.toString();
    }

    protected String getSQLBuscarPorId() {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT * ");
        sql.append(" FROM editor ");
        sql.append(" WHERE id = ? ");
        return sql.toString();
    }

    private static String getSQLBuscarPorLogin() {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT * ");
        sql.append(" FROM editor ");
        sql.append(" WHERE usuario = ? ");
        sql.append(" AND senha = ? ");
        return sql.toString();
    }
    // </editor-fold>

    // BEGIN: CRUD
    //<editor-fold defaultstate="expanded" desc="Metodos CRUD.">
    public void buscar() throws SQLException, EntidadeNaoEncontrada {
        getConexao();
        PreparedStatement query = getConexao().prepareStatement(getSQLBuscarPorId());
        query.setInt(1, this.getId()); // id
        ResultSet result = query.executeQuery();
        if (result.next()) {
            this.setId(result.getInt("id"));
            this.setUsuario(result.getString("usuario"));
            this.setSenha(result.getString("senha"));
            this.setNome(result.getString("nome"));
        } else {
            throw new EntidadeNaoEncontrada();
        }
    }

    public void salvar() throws SQLException {
        getConexao();
        conexao.setAutoCommit(false);
        inserir();
        conexao.commit();
    }

    private void inserir() throws SQLException {
        PreparedStatement query = getConexao().prepareStatement(getSQLInsercao(), Statement.RETURN_GENERATED_KEYS);
        query.setString(1, this.getUsuario()); // usuario
        query.setString(2, this.getSenha()); // senha
        query.setString(3, this.getNome()); // nome
        query.executeUpdate();
        ResultSet result = query.getGeneratedKeys();
        result.first();
        int result_id = result.getInt(1);
        this.setId(result_id);
    }

    public void alterar() throws SQLException {
        getConexao();
        conexao.setAutoCommit(false);
        atualizar();
        conexao.commit();
    }

    private void atualizar() throws SQLException {
        PreparedStatement query = getConexao().prepareStatement(getSQLAtualizacao());
        query.setString(1, this.getUsuario()); // usuario
        query.setString(2, this.getSenha()); // senha
        query.setString(3, this.getNome()); // nome
        query.setInt(4, this.getId()); // id
        query.executeUpdate();
    }

    public void remover() throws SQLException {
        getConexao();
        conexao.setAutoCommit(false);
        excluir();
        conexao.commit();
    }

    private void excluir() throws SQLException {
        PreparedStatement query = getConexao().prepareStatement(getSQLExclusao());
        query.setInt(1, this.getId()); // id
        query.executeUpdate();
    }
    // </editor-fold>
    // END: CRUD
}
